<template>
  <div class="science-chat-page">
    <div class="chat-container">
      <!-- 聊天记录侧边栏按钮 -->
      <button 
        v-if="!isSidebarOpen"
        class="sidebar-toggle" 
        @click="toggleSidebar"
        :class="{ open: isSidebarOpen }"
      >
        
      </button>
      
      <!-- 聊天记录侧边栏 -->
      <div class="sidebar" :class="{ open: isSidebarOpen }">
        <div class="sidebar-header">
          <h2>聊天记录</h2>
          <button class="sidebar-close" @click="toggleSidebar"><<</button>
        </div>
        <ul class="chat-history-list">
          <li 
            v-for="(record, index) in chatHistory" 
            :key="index"
            class="chat-history-item"
            @click="jumpToMessage(record.id)"
          >
            <div class="chat-history-question">{{ record.question }}</div>
            <div class="chat-history-time">{{ record.time }}</div>
            <button class="delete-history-btn" @click.stop="deleteHistoryItem(record.id)">×</button>
          </li>
        </ul>
      </div>

      <!-- 初始欢迎界面 -->
      <div v-if="isInitialPage" class="initial-welcome">
        <div class="welcome-message">
          您好！我是火星科普大模型，专门为您提供准确的火星科学知识。您可以问我关于火星的地质、气候、探索历史等任何问题。
        </div>
        <div class="input-container centered">
          <div class="input-wrapper">
            <el-input
              v-model="inputMessage"
              @keyup.enter="sendMessage"
              placeholder="请输入您的问题..."
              :disabled="isLoading"
              class="message-input"
              type="textarea"
              :rows="1"
            />
            <el-button
              class="send-button"
              @click="sendMessage"
              :disabled="!inputMessage.trim() || isLoading"
              :loading="isLoading"
              type="primary"
              title="发送消息,按 Enter 发送消息，Shift + Enter 换行"
            >
              <el-icon><Promotion /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 标准聊天界面 -->
      <template v-else>
        <div class="chat-messages" ref="chatMessages">
          <div
            v-for="message in messages"
            :key="message.id"
            :ref="setMessageElement(message.id)"
            :class="['message', message.type]"
          >
            <div class="message-content" v-if="message.type !== 'system' || message.content">
              <div class="message-text" v-html="message.content"></div>
              <!-- 展示图片 -->
              <div v-if="message.images && message.images.length > 0" class="message-images">
                <div class="images-title">相关图片：</div>
                <div class="images-container">
                  <img
                    v-for="(image, index) in message.images"
                    :key="index"
                    :src="image"
                    :alt="`图片 ${index + 1}`"
                    class="message-image"
                    @click="openImageModal(image)"
                  />
                </div>
              </div>
              <div v-if="message.questions && message.questions.length > 0" class="suggested-questions">
                <div class="questions-title">相关问题：</div>
                <div class="question-buttons">
                  <button
                    v-for="(question, index) in message.questions"
                    :key="index"
                    @click="handleQuestionClick(question)"
                    class="question-btn"
                  >
                    {{ question }}
                  </button>
                </div>
              </div>
              <div class="message-time" v-if="message.type !== 'system'">{{ message.time }}</div>
            </div>
          </div>

          <div v-if="isLoading" class="message assistant">
            <div class="message-content">
              <div class="message-text typing">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input-area">
          <div class="input-container">
            <div class="input-wrapper">
              <el-input
                v-model="inputMessage"
                @keyup.enter="sendMessage"
                placeholder="请输入您的问题..."
                :disabled="isLoading"
                class="message-input"
                type="textarea"
                :rows="1"
              />
              <el-button 
                class="clear-button" 
                @click="clearMessages"
                title="清空对话"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
              <el-button
                class="send-button"
                @click="sendMessage"
                :disabled="!inputMessage.trim() || isLoading"
                :loading="isLoading"
                type="primary"
                title="发送消息,按 Enter 发送消息，Shift + Enter 换行"
              >
                <el-icon><Promotion /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </template>
    </div>
    
    <!-- 图片预览模态框 -->
    <div v-if="showImageModal" class="image-modal" @click="closeImageModal">
      <div class="image-modal-content" @click.stop>
        <button class="image-modal-close" @click="closeImageModal">×</button>
        <img :src="currentImage" alt="预览图片" class="modal-image" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, reactive } from 'vue'
import api from '../api/index.js'
import { Delete, Promotion } from '@element-plus/icons-vue'

// 消息类型定义
interface ChatMessage {
  id: string
  type: 'user' | 'assistant' | 'system'
  content?: string
  time?: string
  questions?: string[]
  images?: string[]  // base64 图片数组
}

// 聊天记录条目类型定义
interface ChatHistoryItem {
  id: string
  question: string
  time: string
}

// 为组件添加name，以便keep-alive可以正确缓存
defineOptions({
  name: 'ScienceChat'
})

// 响应式数据
const inputMessage = ref('')
const isLoading = ref(false)
const chatMessages = ref<HTMLElement>()
const isSidebarOpen = ref(true); // 默认展开侧边栏
const messageElements = reactive<{[key: string]: HTMLElement}>({})

// 仅在元素为 HTMLElement 时记录引用，避免 TS 类型不匹配
const setMessageElement = (id: string) => (el: Element | any | null) => {
  const dom: Element | null = el && el.$el ? el.$el : el
  if (dom instanceof HTMLElement) {
    messageElements[id] = dom
  }
}

// 从配置文件获取API URL
const apiUrl = ref(window.ScienceChat_URL) // 默认值

// 判断是否为初始页面（只有系统欢迎消息且内容为空）
const isInitialPage = computed(() => {
  return messages.value.length === 1 && 
         messages.value[0]?.type === 'system' && 
         !messages.value[0]?.content
})

// 消息列表 - 从 sessionStorage 中获取或使用默认值
const getInitialMessages = () => {
  const savedMessages = sessionStorage.getItem('scienceChatMessages')
  if (savedMessages) {
    try {
      return JSON.parse(savedMessages)
    } catch (e) {
      console.error('Failed to parse saved messages', e)
    }
  }
  
  return [
    {
      id: '1',
      type: 'system',
      content: '',
      time: new Date().toLocaleTimeString()
    }
  ]
}

const messages = ref<ChatMessage[]>(getInitialMessages())

// 计算聊天历史记录（仅包含用户消息）
const chatHistory = computed(() => {
  const history: ChatHistoryItem[] = []
  messages.value.forEach(message => {
    if (message.type === 'user' && message.content) {
      history.push({
        id: message.id || '',
        question: message.content,
        time: message.time || ''
      })
    }
  })
  // 按时间倒序排列（最新的在前面）
  return history.reverse()
})

// 监听消息变化并保存到 sessionStorage
const saveMessages = () => {
  try {
    sessionStorage.setItem('scienceChatMessages', JSON.stringify(messages.value))
  } catch (e) {
    console.error('Failed to save messages', e)
  }
}

// 清空聊天记录
const clearMessages = () => {
  messages.value = []
  saveMessages() // 保存清空后的消息到 sessionStorage
}

// 切换侧边栏显示状态
const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value;
}

// 跳转到指定消息
const jumpToMessage = (messageId: string) => {
  const targetElement = messageElements[messageId];
  if (targetElement) {
    // 滚动到目标元素
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    });
    
    // 添加高亮效果
    targetElement.classList.add('highlight');
    setTimeout(() => {
      targetElement.classList.remove('highlight');
    }, 3000);
  }
}

// 删除历史记录项
const deleteHistoryItem = (messageId: string) => {
  // 显示确认对话框
  if (confirm('确定要删除这条聊天记录吗？')) {
    // 查找要删除的消息索引
    const messageIndex = messages.value.findIndex(msg => msg.id === messageId);
    if (messageIndex !== -1) {
      // 只删除该用户消息（保留之前的系统消息和用户消息）
      // 找到下一条用户消息，如果没有则删除到末尾
      let endIndex = messages.value.length;
      for (let i = messageIndex + 1; i < messages.value.length; i++) {
        const msg = messages.value[i]
        if (msg && msg.type === 'user') {
          endIndex = i;
          break;
        }
      }
      
      // 删除从该用户消息开始到下一条用户消息（或末尾）的所有消息
      messages.value.splice(messageIndex, endIndex - messageIndex);
      
      // 保存更新后的消息到 sessionStorage
      saveMessages();
    }
  }
}

// 方法
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  // 如果是初始状态，移除初始的系统消息
  if (isInitialPage.value) {
    messages.value = []
  }
  // 添加用户消息
  addMessage('user', userMessage)
  // 显示加载状态
  isLoading.value = true
  try {
    // 构建请求数据，匹配后端 ChatRequest 格式
    const requestData = {
      message: userMessage,
      history: []  // 可以后续添加历史记录支持
    }
    const response = await fetch(apiUrl.value, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const result = await response.json()
    // 接收后端返回的 message、questions 和 images
    addMessage(
      'assistant', 
      result.message || result.answer || '抱歉，未获取到回复。',
      result.questions || [],
      result.images || []
    )
  } catch (error) {
    console.error('Chat error:', error)
    addMessage('system', '科普大模型暂时无法使用，请稍后再试。')
  } finally {
    isLoading.value = false
  }
}

// 解析链接格式，将 \url{https://xxx} 转换为文献引用格式
const parseLinks = (text: string): { content: string, references: string[] } => {
  const references: string[] = []
  let referenceIndex = 1

  // 匹配 \url{https://xxx} 格式
  const urlRegex = /\\url\{([^}]+)\}/g
  const content = text.replace(urlRegex, (match, url) => {
    references.push(url)
    const index = referenceIndex++
    return `<sup><a href="${url}" target="_blank" rel="noopener noreferrer" style="color: #007bff; text-decoration: none;">[${index}]</a></sup>`
  })

  return { content, references }
}

const addMessage = (type: 'user' | 'assistant' | 'system', content: string, questions?: string[], images?: string[]) => {
  const { content: parsedContent, references } = parseLinks(content)

  // 如果有参考文献，添加到内容末尾
  let finalContent = parsedContent
  if (references.length > 0) {
    finalContent += '<div class="references" style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #e0e0e0; font-size: 0.9em; color: #666;">'
    finalContent += '<strong>参考文献：</strong><br>'
    references.forEach((url, index) => {
      finalContent += `[${index + 1}] <a href="${url}" target="_blank" rel="noopener noreferrer" style="color: #007bff; text-decoration: underline;">${url}</a><br>`
    })
    finalContent += '</div>'
  }

  const message = {
    id: Date.now().toString(),
    type,
    content: finalContent,
    time: new Date().toLocaleTimeString(),
    questions: questions || [],
    images: images || []
  }
  messages.value.push(message)
  saveMessages() // 保存消息到 sessionStorage
  nextTick(() => {
    scrollToBottom()
  })
}

const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}


// 处理问题点击
const handleQuestionClick = (question: string) => {
  inputMessage.value = question
  sendMessage()
}

// 图片预览模态框相关
const showImageModal = ref(false)
const currentImage = ref('')

const openImageModal = (imageSrc: string) => {
  currentImage.value = imageSrc
  showImageModal.value = true
}

const closeImageModal = () => {
  showImageModal.value = false
  currentImage.value = ''
}

onMounted(async () => {
  console.log('Science chat page mounted')
  await api.loadApiConfig()
})
</script>

<style scoped>
.science-chat-page {
  height: calc(100vh - 80px);
  display: flex;
  overflow: hidden;
  padding: 0;
  background: white;
  position: relative;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-width: 850px;
  margin: 0 auto;
  background: white;
  border-radius: 10px;
  /* box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); */
  overflow: hidden;
  position: relative;
}

/* 聊天记录侧边栏按钮 */
.sidebar-toggle {
  position: fixed;
  left: 10px;
  top: 105px; 
  background-color: #fff;
  color: #333;
  border: 3px solid #ddd;
  border-radius: 0 15px 15px 0;
  padding: 10px 15px;
  cursor: pointer;
  z-index: 1001;
  font-size: 18px;
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sidebar-toggle.open {
  left: 400px;
}

.sidebar-toggle::before {
  content: ">>";
  font-size: 20px;
}

.sidebar-toggle.open::before {
  content: "<<";
}

/* 移除 hover 和 active 状态下的边框变化 */
.sidebar-toggle:hover {
  color:red;
  border-color: #ddd;
  background-color: #f5f5f5;
}

/* 聊天记录侧边栏 */
.sidebar {
  position: fixed;
  left: -400px;
  top: 80px;
  width: 400px;
  height: calc(100vh - 80px);
  background-color: white;
  box-shadow: 2px 0 5px rgba(0,0,0,0.1);
  z-index: 1000;
  overflow-y: auto;
  transition: left 0.3s ease;
  display: flex;
  flex-direction: column;
}

.sidebar.open {
  left: 0;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
}

.sidebar-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
  padding: 5px 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  color: #333;
  border: 3px solid #ddd;
}

.sidebar-close:hover {
  color: #333;
  background-color: #f5f5f5;
}

.chat-history-list {
  list-style: none;
  padding: 0;
  margin: 0;
  flex: 1;
  overflow-y: auto;
}

.chat-history-question {
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left; /* 确保问题文本左对齐 */
}

.chat-history-time {
  font-size: 12px;
  color: #999;
  text-align: left; /* 确保时间文本左对齐 */
}

.delete-history-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.delete-history-btn:hover {
  color: #ff4d4f;
  background-color: #f5f5f5;
}

.chat-history-item {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative; /* 添加这行以便定位删除按钮 */
}

.chat-history-item:hover {
  background-color: #f5f5f5;
}

.chat-history-item:last-child {
  border-bottom: none;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: white;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  gap: 15px;
  max-width: 100%;
}

.message.highlight {
  animation: highlight 2s ease;
}

@keyframes highlight {
  0% { 
    background-color: #ffeb3b;
    box-shadow: 0 0 15px rgba(255, 235, 59, 0.5);
  }
  50% {
    background-color: #fff176;
    box-shadow: 0 0 25px rgba(255, 235, 59, 0.8);
  }
  100% { 
    background-color: transparent;
    box-shadow: 0 0 5px rgba(255, 235, 59, 0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}


.message-content {
  max-width: 100%;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.assistant, .message.system {
  align-self: flex-start;
}

.system {
  justify-content: center;
  width: 100%;
}

.message-text {
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.5;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
  white-space: pre-wrap;
  max-width: 100%;
}

.user .message-text {
  background: #f5f7f9;
  color: #333;
  border-top-right-radius: 4px;
}

.assistant .message-text {
  background: white;
  color: #333;
  border-top-left-radius: 4px;
  border: 1px solid #e0e0e0;
}

.system .message-text {
  background: #e8f4ff;
  color: #333;
  border-radius: 12px;
  font-style: italic;
  max-width: 90%;
  margin: 0 auto;
  text-align: center;
}

.message-time {
  font-size: 0.8rem;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.user .message-time {
  text-align: right;
}

.assistant .message-time {
  text-align: left;
}

.system .message-time {
  text-align: center;
}

.typing {
  display: flex;
  align-items: center;
  gap: 4px;
}

.typing span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input-area {
  padding: 30px;
  background: white;
  /* border-top: 1px solid #e0e0e0; */
}

.initial-welcome {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
  text-align: center;
}

.welcome-message {
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 30px;
  line-height: 1.6;
  max-width: 80%;
}

.input-container.centered {
  width: 100%;
  max-width: 600px;
}

.input-container.centered .input-wrapper {
  justify-content: center;
}

.input-container {
  margin-bottom: 8px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

.message-input {
  flex: 1;
  min-width: 0;
}

.message-input :deep(.el-textarea__inner) {
  min-height: 42px !important;
  height: 42px;
  resize: none;
  font-size: 14px; /* 增大字体以适应输入框高度 */
  /* line-height: 42px; 设置合适的行高 */
  padding: 10px 15px; /* 调整内边距使文字居中 */
}

.clear-button,
.send-button {
  height: 42px;
  width: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 6px;
  transition: all 0.3s;
}

.clear-button {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  color: #909399;
}

.clear-button:hover {
  background-color: #eee;
  border-color: #c0c4cc;
  color: #606266;
}

.send-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  flex-shrink: 0;
}

.send-button:hover:not(:disabled) {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 添加加载状态下的样式，确保按钮宽度不变 */
.send-button :deep(.el-button__loading) {
  position: absolute;
  margin-left: -50%;
  margin-top: -50%;
}

.send-button :deep(.el-button__loading + span) {
  visibility: hidden;
}

/* 图片展示样式 */
.message-images {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.images-title {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 10px;
  font-weight: 600;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  object-fit: cover;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.message-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-color: #007bff;
}

/* 图片预览模态框 */
.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  cursor: pointer;
}

.image-modal-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: default;
}

.image-modal-close {
  position: absolute;
  top: -40px;
  right: 0;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  font-size: 24px;
  color: #333;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 2001;
}

.image-modal-close:hover {
  background: white;
  transform: rotate(90deg);
}

.modal-image {
  max-width: 100%;
  max-height: 90vh;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

/* 建议问题样式 */
.suggested-questions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.questions-title {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 10px;
  font-weight: 600;
}

.question-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-btn {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 10px 15px;
  font-size: 0.9em;
  color: #495057;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
  line-height: 1.4;
  word-wrap: break-word;
}

.question-btn:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  border-color: #adb5bd;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.question-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .science-chat-page {
    padding: 0;
  }

  .page-header h1 {
    font-size: 2rem;
  }

  .chat-container {
    height: 100%;
    border-radius: 0;
  }

  .chat-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }

  .chat-controls {
    justify-content: center;
  }

  .message-text {
    max-width: 90%;
  }

  .user .message-text {
    max-width: 85%;
  }

  .question-btn {
    font-size: 0.85em;
    padding: 8px 12px;
  }
  
  .sidebar {
    width: 100%;
    left: -100%;
  }
  
  .sidebar.open {
    left: 0;
  }
  
  .sidebar-toggle.open {
    left: 100%;
  }
}
</style>